import MINI_PROGRAM_CONFIG from '../env.js'
const defaultBaseUrl = MINI_PROGRAM_CONFIG.WX_BASE_URL
const methods = {
  'get': 'GET',
  'post': 'POST',
  'put': 'PUT',
  'delete': 'DELETE'
}

const abnormalHandler = ({url, data, res}) => {
  console.error(url, 'url')
  console.error(data, 'data')
  console.error(getApp().globalData.token, 'token')
  console.log(res, 'res')
  wx.showToast({
    title: res.msg,
    icon: 'none',
    image: '',
    duration: 1500,
    mask: true
  })
}

const errorHandler = error => {
  wx.showToast({
    title: '服务繁忙，请稍后再试',
    icon: 'none',
    image: '',
    duration: 2000,
    mask: true
  })
}

let isRefreshing = true;
function checkStatus(url, method, data, header, baseUrl, response) {
  if (response && response.code === '000-1002-400' || response.code === '000-1002-401') {
    //401 登录失败
    // 刷新token的函数,这需要添加一个开关，防止重复请求
    if(isRefreshing){
      loginAgain()
    }
    if(!isRefreshing){
      retryOriginalRequest = new Promise((resolve) => {
        addSubscriber(() => {
          resolve(request({ url, method, data, header, baseUrl }))
        })
    });
    }
    isRefreshing = false;
    console.log('data',response)
    wx.showToast({
      title: response.msg,
      icon: 'none',
      image: '',
      duration: 2000,
      mask: true
    })
    // 这个Promise函数很关键
    
    return retryOriginalRequest;
  } else {
      abnormalHandler({
        data,
        url,
        res: response.data
      })
  }
}


const loginAgain = () => {
  wx.login({
    success(res) {
      if (res.code) {
        wx.request({
          url: defaultBaseUrl + '/user/getToken',
          data: { code: res.code },
          header: {
            'content-type': 'application/x-www-form-urlencoded'
          },
          timeout: 300000,
          method: 'post',
          success: (sucRes => {
            wx.setStorageSync('token', sucRes.data.data.token)
            getApp().globalData.token = sucRes.data.data.token
            onAccessTokenFetched()
            isRefreshing = false
          }),
          fail: (failRes => {
            errorHandler(failRes)
          })
        })
      }
    }
  })
}

let subscribers = [];
function onAccessTokenFetched() {
    subscribers.forEach((callback) => {
        callback();
    })
    subscribers = [];
}

function addSubscriber(callback) {
    subscribers.push(callback)
}



const request = ({ url, method, data, header, baseUrl }) => {
  return new Promise((resolve, reject) => {
    const requestBaseUrl = !baseUrl ? defaultBaseUrl : baseUrl
    const newHeader = Object.assign({
      'content-type': 'application/json',
      'token': wx.getStorageSync('token') || getApp().globalData.token || null
    },header)
    const requestTask = wx.request({
      url: requestBaseUrl + url,
      data: data,
      header: newHeader,
      timeout: 300000,
      method: methods[method],
      success: (res => {
        console.log('token:', getApp().globalData.token)
        console.log('接口', url)
        console.log('传参', data)
        console.log('接收数据', res.data)
        switch (res.data.code) {
          case '1':
            resolve(res.data.data)
            break
          case '001-4001-003':
            reject(res.data.data)
            break
          default:
            resolve(checkStatus( url, method, data, header, baseUrl, res.data ))
        }
      }),
      fail: (res => {
        errorHandler(res)
      })
    })
    requestTask.onHeadersReceived((res) => {
      console.log('TraceId', res.header.Trace)
    })
  })
}

export default request
